/**
 * Created by Administrator on 2019/3/28.
 */
var table;
var t = 1;
$(function () {
    table = $("#limitsList");
    intiGrid();
    initLimits();
});

var intiGrid = function () {
    var toolbar = [{
        text:'保存',
        iconCls:'icon-save',
        handler:function(){saveLimitsOfRole();}
    },'-',{
        text:'重置',
        iconCls:'icon-reload',
        handler:function(){}
    }];
    table.treegrid( {
        iconCls : 'icon-file',
        idField:'id',
        treeField:'limitName',
        striped : true,
        collapsible : false,
        fitColumns :true,
        singleSelect : false,
        animate:true,
        checkOnSelect : true,
        selectOnCheck : true,
        dataPlain : true,
        border:false,
        columns : [ [  {
            field : 'id',
            checkbox : false,
            hidden:true
        }, {
            title : '菜单名称',
            field : 'limitName',
            width : 150
        }, {
            title : '选择',
            field : 'chk',
            width : 50,
            formatter :function (value,row,index) {
                return "<input type='checkbox' onclick=relatedChoice('" + row.id + "') id='check_" + row.id + "'/>";
            }
        }
        ] ],
        toolbar:toolbar,
        onBeforeLoad:function() {
            var param = [];
            var json = postSyncAjax("/findLimitsByParentCode/minus",null).data;
            //console.log(json);
            var limit = json.data;
            for(var i = 0; i<limit.length; i++){
                var iconCls;
                if (limit[i].limitType == "page") {
                    iconCls = "tree-folder";
                } else if (limit[i].limitType == "button") {
                    iconCls = "icon-file";
                } else {
                    iconCls = "icon-file";
                }
                param.push({
                    "id": limit[i].id, "limitName": limit[i].limitName,
                    "icon": limit[i].icon, "url": limit[i].addr,
                    "state": "closed", "limitSort": limit[i].limitSort,
                    "t": t, "limitCode": limit[i].limitCode,
                    "described": limit[i].described, iconCls: iconCls,
                    "parentCode":limit[i].parentCode
                });
            }
            //console.log(param);
            table.treegrid('loadData', param);
            table.treegrid("expandAll");
        },
        onBeforeExpand : function(note) {
            //console.log(note);
            if(note.t==1) {
                userTreeLoad(note);
            }
        }
    });

}

var initLimits = function () {
    var rolesId = $("#rolesId").val();
    console.log(rolesId);
    var params = new Object();
    params.rolesId = rolesId;
    var jsonStr = postSyncAjax("/selectRoleLimitByPage/normal/", params);
    if(jsonStr.success) {
        var nodes = $("input:checkbox");
        $.each(nodes,function (index,ele) {
            var id = $(ele).attr("id");
            id = id.replace(/check_/g, "");
            var roleLimit = jsonStr.data;
            if(null == roleLimit || undefined == roleLimit) return;
            for(var i = 0; i<roleLimit.length; i++){
                var limitId = roleLimit[i].limitId;
                if(id==limitId) {
                    var s = '#check_' + limitId;
                    $(s)[0].checked = true;
                    break;
                }
            }
        });
    }
}


function userTreeLoad(note) {
    var param = new Array();
    var json = postSyncAjax("/findLimitsByParentCode/"+note.limitCode,null).data;
    var limit = json.data;
    for(var i = 0; i<limit.length; i++){
        if(limit[i].limitCode == note.limitCode) {
            note.described = limit[i].described;
        } else {
            var iconCls;
            if(limit[i].limitType=="page") {
                iconCls = "tree-folder";
            } else if(limit[i].limitType=="button") {
                iconCls = "icon-file";
            } else {
                iconCls = "icon-file";
            }
            param.push({
                "id" : limit[i].id,"limitName" : limit[i].limitName,"icon" : limit[i].icon,
                "url" : limit[i].addr,"state" : "closed","limitSort" : limit[i].limitSort,
                "t":t,"limitCode":limit[i].limitCode,
                "described":limit[i].described,iconCls: iconCls,
                "parentCode":limit[i].parentCode
            });
        }
    }
    $('#limitsList').treegrid('append', {
        parent : note.id,
        data : param
    });
    note.t =2;
    table.treegrid("expandAll");
}

var saveLimitsOfRole = function () {
    var nodes = $("input:checkbox");
    var ids = "";
    $.each(nodes,function (index,ele) {
        if($(ele)[0].checked) {
            var id = $(ele).attr("id");
            id = id.replace(/check_/g, "");
            console.log(id);
            ids = ids + "," + id;
        }
    });
    if(ids == "") {
        $.messager.alert("消息提示","请先选择权限再保存！","warning");
        return;
    }
    ids = ids.substring(1, ids.length);
    var rolesId = $("#rolesId").val();
    console.log("测试："+ids);
    var params = new Object();
    params.rolesId = rolesId;
    params.ids = ids;
    var jsonStr = postSyncAjax("/saveRoles/normal/", params);
    console.log("测试："+jsonStr);
    console.log("测试："+jsonStr.success);
    if(jsonStr.success) {
        $.messager.alert("消息提示","保存成功！","info");
    } else {
        if (jsonStr.status == 401) {
            $.messager.alert("消息提示",jsonStr.msg,"warning",
                function () {
                    window.top.location.href = "/index";
                });
        }
        $.messager.alert("消息提示","保存失败：" + jsonStr.msg,"warning");
        return;
    }
}
// 关联的选择：父节点选中之后，子节点也被选中
function relatedChoice(checkid) {
    var s = '#check_' + checkid;
    /*父节点影响子节点*/
    var nodes = table.treegrid("getChildren", checkid);
    if($(s)[0].checked) {
        var parent = table.treegrid("getParent", checkid);
        if(null != parent && undefined != parent) {
            for (var i = 0; i < nodes.length; i++) {//当父节点取消选中，则其孩子都取消选中
                $('#check_' + nodes[i].id)[0].checked = $(s)[0].checked;
            }
            //console.log(parent);
            if(parent.parentCode == -1) {
                $('#check_' + parent.id)[0].checked = $(s)[0].checked;
            }
        }
    } else {
        for (var i = 0; i < nodes.length; i++) {//当父节点取消选中，则其孩子都取消选中
            $('#check_' + nodes[i].id)[0].checked = $(s)[0].checked;
        }
    }

    /*子节点影响父节点*/
    if ($(s)[0].checked) {//如果子节点全部被选中，则父节点被选中
        var parent = table.treegrid("getParent", checkid);
        var flag = true;
        while(flag) {
            if(null != parent && undefined != parent && null != parent.described && "" != parent.described) {
                var sons = parent.described.split(',');
                for (var j = 0; j < sons.length; j++) {//如果子节点中存在没有选中的，则flag为false
                    if (!($('#check_' + sons[j])[0].checked)) {
                        flag = false;
                        break;
                    }
                }
                if (flag){
                    $('#check_' + parent.id)[0].checked = true;//如果子节点中不存在没有选中的，则flag为true，父节点被选中
                    parent = table.treegrid("getParent", parent.id);
                }
            } else {
                flag = false;
            }
        }
    }
}


// 关联的选择：父节点选中之后，子节点也被选中
function relatedChoice1(checkid) {
    var s = '#check_' + checkid;
    /*选子节点*/
    var nodes = table.treegrid("getChildren", checkid);
    for (var i = 0; i < nodes.length; i++) {//当父节点被选中，则其孩子都被选中
        $('#check_' + nodes[i].id)[0].checked = $(s)[0].checked;
    }
    //选上级节点
    if (!$(s)[0].checked) {//如果子节点中有没有选中的，则父节点就不会被选中
        var parent = table.treegrid("getParent", checkid);
        if(null != parent && undefined != parent) {
            $(('#check_' + parent.id))[0].checked = false;
        }
        while (parent) {
            parent = table.treegrid("getParent", parent.id);
            if(null != parent && undefined != parent) {
                $(('#check_' + parent.id))[0].checked = false;
            }
        }
    } else {//如果子节点全部被选中，则父节点被选中
        var parent = table.treegrid("getParent", checkid);
        var flag = true;
        while(flag) {
            if(null != parent && undefined != parent && null != parent.described && "" != parent.described) {
                var sons = parent.described.split(',');
                for (var j = 0; j < sons.length; j++) {//如果子节点中存在没有选中的，则flag为false
                    if (!($('#check_' + sons[j])[0].checked)) {
                        flag = false;
                        break;
                    }
                }
                if (flag){
                    $('#check_' + parent.id)[0].checked = true;//如果子节点中不存在没有选中的，则flag为true，父节点被选中
                    parent = table.treegrid("getParent", parent.id);
                }
            } else {
                flag = false;
            }
        }
    }
}